﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using MVVM.Core;
using ObjectModel.PowerPoint;
using System.Windows.Forms.Integration;

namespace ViewModels
{
    public class PPTViewModelManager
    {
        readonly Ppt.Application mApp = Globals.Application;
        readonly Dictionary<Ppt.Presentation, ViewModelBase> mViewModels = new Dictionary<Ppt.Presentation, ViewModelBase>();
        readonly ElementHost mHostControl;

        public PPTViewModelManager(ElementHost hostControl)
        {
            mHostControl = hostControl;
            
            //add any presentations already open to the dictionary
            foreach (Ppt.Presentation pres in mApp.Presentations)
                Add(pres);
            
            HookUpEvents();
        }

        private ViewModelBase ActiveViewModel
        {
            set
            {
                mHostControl.Child = value.View;
            }
        }

        void Add(Ppt.Presentation pres)
        {
            if (!mViewModels.ContainsKey(pres))
            {
                //ViewModelBase viewModel = ViewModelFactory.CreateViewModel<DataLinksViewModel, DataLinksControl>();
                ViewModelBase viewModel = new ViewModelBase();
                mViewModels.Add(pres, viewModel);

                ActiveViewModel = viewModel;
            }
        }

        void Remove(Ppt.Presentation pres)
        {
            if (mViewModels.ContainsKey(pres))
                mViewModels.Remove(pres);
        }

        void HookUpEvents()
        {
            mApp.AfterNewPresentation += App_AfterNewPresentation;
            mApp.PresentationOpen += App_PresentationOpen;
            mApp.PresentationClose += App_PresentationClose;
            mApp.WindowActivate += App_WindowActivate;
        }

        void App_AfterNewPresentation(Ppt.Presentation Pres)
        {
            Add(Pres);
        }

        void  App_PresentationOpen(Ppt.Presentation Pres)
        {
            Add(Pres);
        }

        void App_PresentationClose(Ppt.Presentation Pres)
        {
            Remove(Pres);
        }

        void App_WindowActivate(Ppt.Presentation Pres, Ppt.DocumentWindow Wn)
        {
            ViewModelBase viewModel;
            if (mViewModels.TryGetValue(Pres, out viewModel))
                ActiveViewModel = viewModel;
        }
    }
}
